package com.chineseall.app.controller;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.CloseReason;
import javax.websocket.Session;

import jmind.core.spring.AbstractController;
import jmind.core.util.RequestUtil;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chineseall.app.ConnectionManager;
import com.chineseall.app.MTypes;
import com.chineseall.app.pojo.mongo.MMessage;
import com.chineseall.app.service.EventService;
import com.chineseall.app.ws.SendMessage;
import com.chineseall.app.ws.WebSocketEndpoint;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Controller
public class HomeController extends AbstractController {

    @Resource
    private EventService eventService;

    @RequestMapping("/")
    @ResponseBody
    public String index(final HttpServletRequest request) {

        Map<String, Object> stats = ConnectionManager.INSTANCE.stats();
        stats.put("startDate", request.getServletContext().getAttribute("startDate"));
        return stats.toString();
    }

    @RequestMapping("/home")
    public String home(final HttpServletRequest request) {
        return "home";
    }

    @RequestMapping("/on")
    @ResponseBody
    public String on(final HttpServletRequest request) {
        int uid = RequestUtil.getParamInt(request, "uid", 0);
        String result = "session is null";
        Session s = null;
        if (uid > 0) {
            WebSocketEndpoint ws = ConnectionManager.INSTANCE.getSession(uid);
            if (ws != null) {
                s = ws.session;
                result = ws.toString();
            }
        } else {
            s = ConnectionManager.INSTANCE.getSession(request.getParameter("sid"));
            if (s != null) {
                result = s.getId() + "--" + s.getUserProperties();
            }
        }

        //   Map<String, Object> map = session.session.getUserProperties();
        //  HandshakeRequest req = (HandshakeRequest) map.get("request");
        //  HandshakeResponse resp = (HandshakeResponse) map.get("response");

        if ("close".equals(request.getParameter("op"))) {
            try {
                s.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "I CLOSE"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @RequestMapping("/send")
    @ResponseBody
    public String send(@RequestParam int uid, @RequestParam String message) {
        MMessage m = new MMessage();
        m.mtype(MTypes.NOTIFY_301);
        m.body(message);
        return SendMessage.send(uid, m) + "";
    }

    @RequestMapping("/fix")
    public String fix(final HttpServletRequest request) {
        Set<Session> sessions = ConnectionManager.INSTANCE.getOpenSessions();
        Map<Integer, Session> maps = Maps.newHashMap();
        List<String> list = Lists.newArrayList();
        for (Session s : sessions) {
            Integer uid = (Integer) s.getUserProperties().get("uid");
            if (maps.containsKey(uid)) {
                list.add(s.getId() + "----" + s.getUserProperties().toString());
                continue;
            }
            maps.put(uid, s);
        }
        request.setAttribute("connections", list);
        return "fix";
    }

    @RequestMapping("/all")
    public String all(final HttpServletRequest request) {
        Set<Session> sessions = ConnectionManager.INSTANCE.getOpenSessions();
        List<String> list = Lists.newArrayList();
        for (Session s : sessions) {
            list.add(s.getId() + "----" + s.getUserProperties().toString());
        }
        request.setAttribute("connections", list);
        return "fix";
    }

    @RequestMapping("/stat")
    public String stat(final HttpServletRequest request) {
        Collection<WebSocketEndpoint> connections = ConnectionManager.INSTANCE.getConnections();
        Map<String, Object> stats = ConnectionManager.INSTANCE.stats();
        request.setAttribute("connections", connections);
        request.setAttribute("stats", stats);
        return "stat";
    }

    @RequestMapping("/startup")
    @ResponseBody
    public String sub(final HttpServletRequest request) {
        eventService.startup();
        return JSON_SUCCESS;
    }

}
